package ruxi.tema1;


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class Tema1 extends ListActivity {
	static CityAdapter adapter;
	boolean noInternet;
	ProgressDialog progressDialog;
	int myPosition;
	String myXML = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //citesc orasele din fisier - in caz ca acesta exista
        if(adapter == null) {
        	adapter = new CityAdapter (this);
        	InputStream in;
			try {
				in = openFileInput("cities");
			
	    	if (in != null) {
		    	InputStreamReader tmp = new InputStreamReader(in);
		    	BufferedReader reader = new BufferedReader(tmp);
		    	String str;
 
		    	
 
		    	while ((str = reader.readLine()) != null) {
		    		adapter.orase.add(str);
		    	}
		    	in.close();
	    	}
	    	} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	
        	
        	
        }
        
        setContentView(R.layout.main);
        setListAdapter (adapter); 
        Button buton = (Button) findViewById(R.id.add_button);
     
        buton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// porneste activitate ce nu ocupa tot ecranul
				Intent intent = new Intent().setClass(Tema1.this, AddCity.class);
				Tema1.this.startActivity(intent);
			}
		});
        Intent intent = this.getIntent();
        String newCity = intent.getStringExtra("cityname");
        
        
        this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> listAdapter, View view,
					int pos, long id) {
				adapter.orase.remove(pos);
				adapter.notifyDataSetChanged();
				writeCitiesToFile();
				return true;
			}
        	 
		});
        
        if(newCity != null){
        	adapter.orase.add(newCity);
        	java.util.Collections.sort(adapter.orase);
        	adapter.notifyDataSetChanged();
        	writeCitiesToFile();	
        }
    }

    
    void writeCitiesToFile() {
    	//rescrie fisierul

    	try {
	    	OutputStreamWriter out = new OutputStreamWriter(openFileOutput("cities", 0));
	    	for(int i = 0; i < adapter.getCount();i++) {
    			out.write(adapter.orase.get(i)+ "\n");
    			
    		}
	    	out.close();
    	} catch (Throwable t) {
    		Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
    	}   
    }
    
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		if(position < adapter.getCount()) {
			this.myPosition= position;
			
			progressDialog = ProgressDialog.show(this, "", "Loading. Please Wait...");
			//creez un thread nou pentru descarcare
			new Thread() {
				public void run()
				{
					myXML = download();
					//dupa finalizarea descarcarii fac dismiss la progressDialog si imi pornesc activitatea noua
					Tema1.this.runOnUiThread(new Runnable() {
						
						@Override
						public void run() 
						{
							progressDialog.dismiss();
								
						        Intent myintent = new Intent(Tema1.this, Forecast.class);
						        myintent.putExtra("mycity", adapter.orase.get(Tema1.this.myPosition));
						        myintent.putExtra("myXML", Tema1.this.myXML);
						        
						        startActivity(myintent);
						        Tema1.this.finish();

							
						}
					});
			
				}
			}.start();
		} else
			super.onListItemClick(l, v, position, id);
	}
    
  String download() {
	  //imi descarc xml-ul si-l returnez ca string
	  HttpGet getMethod=new HttpGet("http://www.google.com/ig/api?weather="+adapter.orase.get(Tema1.this.myPosition));
      HttpClient client = new DefaultHttpClient ();
    	try {

    		ResponseHandler<String> responseHandler=new BasicResponseHandler();
    		String responseBody=client.execute(getMethod, responseHandler);
    		// responseBody reprezinta continutul fisierului RSS luat de pe Internet
    	
    		return responseBody;
    		}
    	catch (Throwable t) {
    		t.printStackTrace();
    		}
    	return null;
  }
}